package cn.ppool.xmlmapper.builder.parse.worker;

import lombok.Getter;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.*;

public class WorkStackRecord {
    LinkedList<WorkStatusRecord> records;
    int stackSize = 500;
    @Getter
    int addCount = 0;
    @Getter
    int errorCount = 0;


    public WorkStackRecord() {
        records = new LinkedList<>();
    }

    public WorkStackRecord(int stackSize) {
        super();
        this.stackSize = stackSize;
    }

    public int size() {
        return records.size();
    }


    public synchronized void add(WorkStatusRecord record) {
        if (size() >= stackSize) {
            records.remove(stackSize - 1);
        }
        addCount++;
        record.setQueryIndex(addCount);
        //
        if (record.getError() != null) {
            errorCount++;
            final Writer result = new StringWriter();
            final PrintWriter printWriter = new PrintWriter(result);
            record.getError().printStackTrace(printWriter);
            String stackTraceStr = result.toString();

            record.setErrorStack(stackTraceStr);
            record.setErrorMessage(record.getError().getMessage());
        }
        records.add(0, record);
    }

    public synchronized void clear() {
        records.clear();
    }

    public synchronized List<WorkStatusRecord> getAll() {
        return records;
    }

    public synchronized LinkedList<WorkStatusRecord> get(int pageNum, int thisPage) {
        LinkedList<WorkStatusRecord> ret = new LinkedList<>();
        int begin = pageNum * thisPage;
        int end = pageNum * thisPage + pageNum;
        for (int i = begin; i < size() && i < end; i++) {
            ret.add(records.get(i));
        }
        return ret;
    }

}
